<template>
	<view class="container">
		<!-- 商品图片 -->
		<view class="" v-if="orderDetail.image && orderDetail.image.length>0">
			<image class="dish-image" :src="orderDetail.image[0].url" mode="aspectFill" />
		</view>
		<!-- 标题与价格 -->
		<view class="dish-info section">
			<view class="title-row">
				<text class="dish-title">{{orderDetail.foodName || ''}}</text>
				<text v-if="orderDetail.huisType==1" style="padding-left: 5rpx;">🐷</text>
				<text v-if="orderDetail.peType==1" style="padding-left: 5rpx;">🌶</text>
				<text v-if="orderDetail.peType==2" style="padding-left: 5rpx;">🌶</text>
				<text v-if="orderDetail.peType==2" style="padding-left: 5rpx;">🌶</text>
				<text v-if="orderDetail.peType==3" style="padding-left: 5rpx;">🌶</text>
				<text v-if="orderDetail.peType==3" style="padding-left: 5rpx;">🌶</text>
				<text v-if="orderDetail.peType==3" style="padding-left: 5rpx;">🌶</text>
				<text class="tag" v-if="orderDetail.isTaste && orderDetail.taste">{{orderDetail.taste}}</text>
			</view>
			<view class="price-row">
				<view class="flex_align_conter" style="display: flex;align-items: center;">
					<!-- <text v-if="orderDetail.isPrice" class=""><text style="font-size: 20rpx;">现售价:</text> ¥ </text>
					<text v-if="orderDetail.isOriginalPrice" class=""><text style="font-size: 20rpx;">原价:</text> ¥ </text> -->
					￥<text v-if="orderDetail.isPrice" class="price"><text class="f18">{{orderDetail.price || 0}}</text> </text>
					<text v-if="orderDetail.isOriginalPrice" class="price"><text style="text-decoration: line-through;font-size: 22rpx;">￥{{orderDetail.originalPrice || 0}}</text> </text>
					<text class="sold-info" style="padding-left: 10rpx;">库存：{{orderDetail.num - orderDetail.sales }}</text>
					<text class="sold-info">销量：{{orderDetail.sales < 0 ? 0 : orderDetail.sales}}</text>
					<text v-if="orderDetail.isSaleAllNum" class="sold-info">累计销量：{{orderDetail.saleAllNum || 0}}</text>
				</view>
				<button v-if="paramsData.lzy_id" class="cu-btn bg-green round add-cart-btn"
					@click="addShoppingCart">加入购物车</button>
			</view>
		</view>
		<!-- 食材介绍 -->
		<view class="section">
			<view class="section-title">菜品介绍</view>
			<view class="section-content" v-if="orderDetail.description">
				{{orderDetail.description || ''}}
			</view>
		</view>
		<!-- 食材清单 -->
		<view class="section" v-if="orderDetail.isFoodIngredientsDishList">
			<view class="section-title flex_between">
				<view class="">
					食材清单
				</view>
				<!-- <view class="view-more">查看全部详情</view> -->
			</view>
			<view class="ingredient-list" v-if="orderDetail.foodIngredientsDishList.length > 0">
				<view class="ingredient-item" v-for="item in orderDetail.foodIngredientsDishList" :key="item.name">
					<text class="name">{{ item.ingredientsName || '' }}</text>
					<text class="weight">{{ item.num || 0}}{{getUnit(item.unit)}}</text>
				</view>
			</view>
		</view>
		<!-- 热量 -->
		<view class="section" v-if="orderDetail.isHeat">
			<view class="section-title">热量</view>
			<view class="section-content">约 {{orderDetail.heat || ''}}千焦 / 份</view>
		</view>
		<!-- 过敏源 -->
		<view class="section" v-if="orderDetail.isAllergy">
			<view class="section-title">过敏源</view>
			<view class="section-content">{{orderDetail.allergy || ''}}</view>
		</view>
		<!-- 规格 -->
		<view class="section" v-if="orderDetail.isPortion">
			<view class="section-title">规格</view>
			<view class="section-content">{{orderDetail.portion || ''}}</view>
		</view>
		<!-- 确认按钮 -->
		<view class="footer">
			<button class="confirm-btn cu-btn bg-green round" @click="goBack">确认</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		getFoodDetailAPI,
		getUnitTypeAPI
	} from '@/api/index.js'
	import {
		listData
	} from "@/api/system/dict/data"
	export default {
		data() {
			return {
				paramsData: {},
				orderDetail: {},
				unitTypeList: [],
				tableCuisine:[]
			};
		},
		onLoad(e) {
			this.paramsData = e
			this.getUnitType()
			this.getFoodDetail()
		},
		computed: {
			...mapState({
				shoppingBagData: state => state.user.shoppingBagData
			}),
		},
		methods: {
			addShoppingCart() {
				if (this.orderDetail.limitPerUser != '-1' && this.paramsData.saleNum >= Number(this
						.orderDetail.limitPerUser))
					return this.$modal.msg('超出限购数量')
				const r = Number(this.orderDetail.num) - Number(this.orderDetail.sales)
				if (this.paramsData.saleNum >= r) return this.$modal.msg('库存不足')
				this.paramsData.saleNum++
				this.handleUpdateNum(this.paramsData.saleNum)
				this.$tab.navigateBack()
			},
			handleUpdateNum(newNum) {

				const newtData = this.updateNumById(newNum)
				this.$store.commit('SET_SHOPPINGBAGDATA', newtData)
				this.$emit('undateData')

			},
			updateNumById(newNum = 0, clearAll = false) {
				return this.shoppingBagData.map(day => {
					const newDay = JSON.parse(JSON.stringify(day))
					const meals = ['meals1', 'meals2']
					const lists = ['comboList', 'dishList']

					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							const list = newDay.dictDataList?.[mealKey]?.[listKey]
							if (Array.isArray(list)) {
								list.forEach(item => {
									// 如果是清空所有，或者当前 item.id 匹配目标 id，就设置 num
									if (clearAll || item.lzy_id === this.paramsData
										.lzy_id) {
										item.saleNum = newNum
									}
								})
							}
						})
					})

					return newDay
				})
			},

			getUnit(e) {
				if (this.unitTypeList.length == 0) return
				const arr = this.unitTypeList.filter(item => item.dictValue == e)
				// const arr = this.unitTypeList.filter(item => {
				// 	console.log(item.dictCode);
				// })
				// console.log(arr);
				return arr[0].dictLabel
			},
			async getUnitType() {
				const res = await getUnitTypeAPI()
				this.unitTypeList = res.data
			},
			insertPropertyByDictLabel(arr, mapping) {
			  // 深拷贝原数组，避免修改原数据
			  return JSON.parse(JSON.stringify(arr)).map(item => {
			    // 检查当前对象是否有dictLabel属性
			    if (item && item.dictLabel !== undefined) {
			      // 查找对应的映射关系
			      const propertyMap = mapping[item.dictLabel];
			      // 如果存在映射关系，则添加对应的属性
			      if (propertyMap && typeof propertyMap === 'object') {
			        return {
			          ...item,
			          ...propertyMap
			        };
			      }
			    }
			    // 如果没有匹配的映射关系，返回原对象
			    return item;
			  });
			},
			updateObjectByDictLabelKey(arr, obj) {
			    // 深拷贝原对象，避免修改原始数据
			    const newObj = JSON.parse(JSON.stringify(obj));
			    
			    // 遍历数组中的每个对象
			    arr.forEach(item => {
			        // 检查当前对象是否有dictLabelKey属性
			        if (item && item.dictLabelKey) {
			            const key = item.dictLabelKey;
			            // 检查目标对象是否包含该属性
			            if (newObj.hasOwnProperty(key)) {
			                // 这里将值改为true，您可以根据需要修改为其他值
			                newObj[key] = true;
			            }
			        }
			    });
			    
			    return newObj;
			},
			async getFoodDetail() {
				const data = await listData({
					dictType: "cuisine_column",
					pageSize: 99,
					pageNum: 1
				})
				console.log(res)
				const S = JSON.parse(JSON.stringify(data.rows));
				this.tableCuisine = S.filter(item=>item.dictValue==1);
				const res = await getFoodDetailAPI(this.paramsData.id)
				// 用于判断是否显示对应字段逻辑
				this.$set(res.data,'isAllergy',false)//是否显示过敏原
				this.$set(res.data,'isHeat',false)//是否显示热量
				this.$set(res.data,'isOriginalPrice',false)//是否显示原价
				this.$set(res.data,'isPrice',false)//是否显示现售价
				this.$set(res.data,'isSaleAllNum',false)//是否显示积累销量
				this.$set(res.data,'isFoodIngredientsDishList',false)//是否显示菜品
				this.$set(res.data,'isPortion',false)//是否显示规格
				this.$set(res.data,'isTaste',false)//是否显示口味
				// 定义映射关系：key是dictLabel的值，value是要插入的属性键值对
				const labelMapping = {
					"食材清单": { 
				    dictLabelKey: 'isFoodIngredientsDishList'
				  },
				  "累计销量": {
				    dictLabelKey: 'isSaleAllNum'
				  },
				  "口味": { 
				    dictLabelKey: 'isTaste'
				  },
				  "热量": { 
				    dictLabelKey: 'isHeat'
				  },
				  "规格": { 
				     dictLabelKey: 'isPortion'
				  },
				  "过敏源": { 
				    dictLabelKey: "isAllergy", 
				  },
				  "现售价": {
				    dictLabelKey: "isPrice", 
				  },
				  "原价": {
				    dictLabelKey: "isOriginalPrice", 
				  }
				};
				// 调用函数
				const result = this.insertPropertyByDictLabel(this.tableCuisine, labelMapping);
				// 调用函数
				const updatedObj = this.updateObjectByDictLabelKey(result, res.data);
				console.log('获取菜品点击过来的------详情----------', this.tableCuisine, res.data, result)
				this.orderDetail = updatedObj
				console.log('获取菜品点击过来的详情', this.orderDetail, updatedObj)
				if (res.data.image) {
					this.orderDetail.image = JSON.parse(res.data.image)
				}
			},
			goBack() {
				this.$tab.navigateBack()
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background: #F2F2F2;
	}

	.dish-image {
		width: 100%;
		// height: 100%;
		height: 600rpx;
		border-radius: 12rpx;
		display: block;
		// margin: 20rpx auto;
	}

	.dish-info {
		margin-top: 20rpx;
		padding: 0 10rpx;

	}

	.title-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.dish-title {
		font-size: 28rpx;
		font-weight: 500;
	}

	.tag {
		margin-left: 10rpx;
		display: inline-block;
		border-radius: 8rpx;
		/* 主色 */
		background: #E6F7F1;
		font-size: 20rpx;
		color: #0EB275;
		padding: 10rpx 20rpx;
	}

	.price-row {
		margin-top: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 26rpx;
		color: #999;

		.sold-info {
			margin-right: 22rpx;
			font-size: 20rpx;
			font-weight: 350;

			/* 次要 */
			color: #848484;
		}
	}

	.price {
		margin-right: 5rpx;
		font-size: 20rpx;
		// color: #e74c3c;
		color: #323232;
	}

	.add-cart-btn {
		padding: 0 20rpx;
		height: 40rpx;
		border-radius: 4rpx;
		font-size: 20rpx;
	}

	.section {

		border-radius: 8rpx;
		padding: 24rpx 32rpx;
		background: #fff;
		margin-top: 30rpx;
	}

	.section-title-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.section-title {
		position: relative;
		font-size: 28rpx;
		font-weight: 500;
		padding-bottom: 20rpx;

	}

	.section-title::before {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 2rpx;
		background-color: #eee;

	}

	.view-more {
		font-size: 24rpx;
		color: #0EB275;
	}

	.section-content {
		margin-top: 16rpx;
		font-size: 20rpx;
		/* 次要 */
		color: #848484;
	}

	.ingredient-list {
		margin-top: 10rpx;
	}

	.ingredient-item {
		display: flex;
		justify-content: space-between;
		padding: 8rpx 0;
		// border-bottom: 1rpx solid #f0f0f0;
		font-size: 24rpx;
		/* 次要 */
		color: #848484;
	}

	.footer {
		text-align: center;
		margin-top: 40rpx;
		padding: 20rpx;
	}

	.confirm-btn {
		// width: 100%;
		padding: 0 100rpx;
		height: 70rpx;
		background: #0EB275;
		color: #fff;
		font-size: 30rpx;
		// border-radius: 16rpx;
	}
</style>